package com.allen.imsystem.message.service.pipeline;

import com.allen.imsystem.chat.service.ChatService;
import com.allen.imsystem.common.Const.GlobalConst;
import com.allen.imsystem.message.model.vo.OneToManyDiffMsgPushPacket;
import com.allen.imsystem.message.model.vo.OneToOneMsgSendPacket;
import com.allen.imsystem.message.model.vo.PushMessageDTO;
import com.allen.imsystem.message.model.vo.SendMsgDTO;
import com.allen.imsystem.message.model.pojo.GroupMsgRecord;
import com.allen.imsystem.chat.service.GroupChatService;
import com.allen.imsystem.message.service.MsgRecordService;
import com.allen.imsystem.message.service.impl.MessageCounter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Component
@Scope("prototype")
public class GroupMsgSaveHandler extends GroupMsgHandler {

    @Autowired
    private GroupChatService groupChatService;

    @Autowired
    private MsgRecordService msgRecordService;

    @Autowired
    private MessageCounter messageCounter;

    @Autowired
    private ChatService chatService;

    @Override
    @Transactional
    public void handleMsg(OneToOneMsgSendPacket<String, SendMsgDTO> msgSendPacket, OneToManyDiffMsgPushPacket<String, PushMessageDTO> msgPacket) {
        SendMsgDTO sendMessage = msgSendPacket.getSendMessage();
        // 2、消息入库
        // 2.1 插入聊天记录 , 并更新该群的最后一条消息
        GroupMsgRecord groupMsgRecord = msgRecordService.saveGroupChatMsgRecord(sendMessage);
        if (sendMessage.getMessageType() != GlobalConst.MsgType.GROUP_NOTIFY) {
            Date preMsgTime =  chatService.getChatLastMsgTimestamp(Long.parseLong(sendMessage.getTalkId()), sendMessage.getGid());
            sendMessage.setPreMsgTime(preMsgTime);
        }
        groupChatService.updateGroupLastMsg(groupMsgRecord.getGid(), groupMsgRecord.getMsgId(),
                groupMsgRecord.getContent(),groupMsgRecord.getCreatedTime(),
                groupMsgRecord.getSenderId());
        // 接收者增加一条未读信息
        messageCounter.incrGroupChatNewMsgCount(sendMessage.getSrcId(),sendMessage.getGid());

    }
}
